package com.lcn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcn.api.feign.FileServiceFeign;
import com.lcn.base.BaseInfoProperties;
import com.lcn.exceptions.GraceException;
import com.lcn.grace.result.ResponseStatusEnum;
import com.lcn.mapper.UsersMapper;
import com.lcn.pojo.Users;
import com.lcn.pojo.bo.UserModifyBO;
import com.lcn.pojo.vo.UsersVO;
import com.lcn.service.UsersService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.UUID;


@Service
@Slf4j
public class UsersServiceImpl extends BaseInfoProperties implements UsersService {

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private FileServiceFeign fileServiceFeign;

    /**
     * 修改用户信息
     *
     * @param userModifyBO
     */
    @Override
    public void modify(UserModifyBO userModifyBO) {
        String userId = userModifyBO.getUserId();
        String wechatNum = userModifyBO.getWechatNum();
        if (StringUtils.isBlank(userId)) {
            GraceException.display(ResponseStatusEnum.USER_INFO_UPDATED_ERROR);
        }
        boolean existWechatNum = StringUtils.isNotBlank(wechatNum);
        Users users = new Users();
        BeanUtils.copyProperties(userModifyBO, users);
        // 如果微信号不为空，需要判断是否在一年内再次更改
        if (existWechatNum) {
            String exist = redis.get(REDIS_USER_ALREADY_UPDATE_WECHAT_NUM + ":" + userId);
            if (StringUtils.isNotBlank(exist)) {
                GraceException.display(ResponseStatusEnum.WECHAT_NUM_ALREADY_MODIFIED_ERROR);
            } else {
                String qrCodeUrl = getQrCode(wechatNum, userId);
                users.setWechatNumImg(qrCodeUrl);
            }
        }
        users.setId(userId);
        usersMapper.updateById(users);
        if (existWechatNum) {
            // 标记为一年内修改过
            redis.setByDays(REDIS_USER_ALREADY_UPDATE_WECHAT_NUM + ":" + userId, userId, 365);
        }
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @param needToken true需要重新设置token
     * @return
     */
    @Override
    public UsersVO getUserInfo(String userId, boolean needToken) {
        // 查询用户最新信息
        Users users = usersMapper.selectById(userId);
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(users, usersVO);
        if (needToken) {
            String userToken = TOKEN_USER_PREFIX + SYMBOL_DOT + UUID.randomUUID();
//            redis.set(REDIS_USER_TOKEN + ":" + userId, userToken); // 单设备登录
            redis.set(REDIS_USER_TOKEN + ":" + userToken, userId); // 多端登录
            usersVO.setUserToken(userToken);
        }
        return usersVO;
    }

    /**
     * 根据微信号或手机号查询用户
     *
     * @param queryString
     * @return
     */
    @Override
    public Users getByWechatNumOrMobile(String queryString) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<Users>()
                .eq("wechat_num", queryString)
                .or()
                .eq("mobile", queryString);
        Users users = usersMapper.selectOne(queryWrapper);
        return users;
    }

    /**
     * 根据id查询用户
     *
     * @param userId
     * @return
     */
    @Override
    public Users getById(String userId) {
        return usersMapper.selectById(userId);
    }

    /**
     * 上传二维码并返回图片地址
     */
    private String getQrCode(String wechatNum, String userId) {
        try {
            String code = fileServiceFeign.generateQrCode(wechatNum, userId);
            return code;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
